#    Copyright 2011 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopip/djangoproject/include', '/opt/coopip/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopip/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject
from djangoproject import settings
setup_environ(settings)
from models import *
#********************Setup psycopg2 and django section********************

from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings
import COOPIP_Misc, COOPIP_Form, COOPIP_Authentication
import djangoproject.models.intranet, djangoproject.models.ipbase, djangoproject.models.revenueprotection
from django.contrib.gis.geos import *
#import GIS

def BuildMessageForm(SpecialBuildFormDataDict):
    Dict={}
    try:
        Message = SpecialBuildFormDataDict['Message']
    except:
        Message=None

    #Only members of the COOPIP_Editor_DepartmentName Group may edit a message, so check the department of the request
    #Against the department of the message (or proposed department) before making any database changes 
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(SpecialBuildFormDataDict['request'], ['COOPIP_RevenueProtectionAdmin', 'COOPIP_Editor_Executive'], True)
    #if(not Permission):  #Do not care about permission, or loginstatus here, just getting the username
    #    return
    EditableMessages=djangoproject.models.intranet.Message().GetAllEditableMessages(SpecialBuildFormDataDict['request'].user).order_by('ArchiveIndicator', 'id')
    SelectMessageChoices=[]
    if(Message and Message in EditableMessages):
        SelectMessageChoices.append([Message.id, str(Message)])
    SelectMessageChoices.append([-1, 'None Selected'])
    for message in EditableMessages:
        if(not [message.id, str(message)] in SelectMessageChoices):
            SelectMessageChoices.append([message.id, str(message)])
    SelectDepartmentChoices=[]
    if(Message):
        SelectDepartmentChoices.append([Message.Department.id, str(Message.Department)])
    Groups=SpecialBuildFormDataDict['request'].user.groups.all()
    Departments=[]
    for group in Groups:
        for department in djangoproject.models.intranet.Department.objects.filter(EditorGroupName=group):
            Departments.append(department)
    for department in Departments:
        SelectDepartmentChoices.append([department.id, str(department)])
    Dict['SelectMessage']=forms.ChoiceField(SelectMessageChoices, required=False)
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['NewIndicator']=forms.BooleanField(required=False)
    Dict['Messageid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5', 'READONLY':'True'}))
    Dict['Title']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'22'}))
    Dict['MessageText']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'6', 'cols':'50'}))
    Dict['Priority']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['FrontPageIndicator']=forms.BooleanField(required=False)
    Dict['DepartmentPageIndicator']=forms.BooleanField(required=False)
    Dict['Department']=forms.ChoiceField(SelectDepartmentChoices, required=False)
    Dict['CreateUsername']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6.5', 'READONLY':'True'}))
    Dict['CreateDateTime']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6.5', 'READONLY':'True'}))
    Dict['LastEditDateTime']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6.5', 'READONLY':'True'}))
    Dict['LastEditUsername']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6.5', 'READONLY':'True'}))
    Dict['ExpireDateTime']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['ArchiveIndicator']=forms.BooleanField(required=False)
    Dict['UploadFile']=forms.FileField()
    Dict['DeleteFile']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['DeleteFileIndicator']=forms.BooleanField(required=False)
    Dict['DepartmentForBackgroundImage']=forms.ChoiceField(SelectDepartmentChoices, required=False)
    Dict['DepartmentBackgroundImage']=forms.FileField()
    SelectEventChoices=[]
    try:
        Event = SpecialBuildFormDataDict['Event']
    except:
        Event=None
    if(Event and Event.Department):
        SelectEventChoices.append([Event.Department.id, str(Event.Department)])
    Groups=SpecialBuildFormDataDict['request'].user.groups.all()
    EditableEvents=djangoproject.models.intranet.Event().GetAllEditableEvents(SpecialBuildFormDataDict['request'].user).order_by('ArchiveIndicator', 'id')
    if(Event and Event in EditableEvents):
        SelectEventChoices.append([Event.id, str(Event)])
    SelectEventChoices.append([-1, 'None Selected'])
    for event in EditableEvents:
        if(not [event.id, str(event)] in SelectEventChoices):
            SelectEventChoices.append([event.id, str(event)])

    SelectEventDepartmentChoices=[]
    EventDepartments=[]
    for group in Groups:
        for department in djangoproject.models.intranet.Department.objects.filter(EditorGroupName=group):
            EventDepartments.append(department)
    for department in Departments:
        if(not department.Name in ['FrontPageBackgroundOnly']):
            SelectEventDepartmentChoices.append([department.id, str(department)])
    Dict['SelectEvent']=forms.ChoiceField(SelectEventChoices, required=False)
    Dict['EventUpdateIndicator']=forms.BooleanField(required=False)
    Dict['EventNewIndicator']=forms.BooleanField(required=False)    
    Dict['EventStaffOnlyIndicator']=forms.BooleanField(required=False)
    Dict['EventName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'25'}))
    Dict['EventDoNotShowBeforeDateTime']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['EventStartDateTime']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['EventEndDateTime']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['EventResource']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['EventDepartment']=forms.ChoiceField(SelectEventDepartmentChoices, required=False)
    Dict['EventFrontPageIndicator']=forms.BooleanField(required=False)
    Dict['EventArchiveOverrideDateTime']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))


    Dict['EventArchiveIndicator']=forms.BooleanField(required=False)
    return Dict

def ProcessMessageForm(form, Username, request):
    SelectMessageid=COOPIP_Form.FormGetInteger(form, 'SelectMessage')
    UpdateIndicator=COOPIP_Form.FormGetBoolean(form, 'UpdateIndicator')
    NewIndicator=COOPIP_Form.FormGetBoolean(form, 'NewIndicator')
    if(NewIndicator):
        SelectedMessage=djangoproject.models.intranet.Message()
    elif(not SelectMessageid == -1 and SelectMessageid):
        SelectedMessage=djangoproject.models.intranet.Message.objects.filter(id=SelectMessageid)[0]
    else:
        SelectedMessage='NoMessageProcessingPossible'

    try:
        UploadFile=request.FILES['UploadFile']
    except:
        UploadFile=None


    try:
        DepartmentBackgroundImage=request.FILES['DepartmentBackgroundImage']
    except:
        DepartmentBackgroundImage=None
    BackgroundDepartment=COOPIP_Form.FormGetObjectFromid(form, 'DepartmentForBackgroundImage', djangoproject.models.intranet.Department)

    if(BackgroundDepartment):
        GroupList=[BackgroundDepartment.EditorGroupName]
        Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, GroupList, True)
    if(BackgroundDepartment and DepartmentBackgroundImage and Permission):
        BaseFileName=str(DepartmentBackgroundImage).split('.')[0]
        Extension=str(DepartmentBackgroundImage).split('.')[-1]
        FileName=str(BaseFileName + '.' + Extension)
        StrippedFileName=[]
        for letter in BackgroundDepartment.Name:
            if(letter.isalnum() or letter in "_"):
                StrippedFileName.append(letter.lower())
        StrippedFileName.append('.')
        for letter in Extension:
            if(letter.isalnum() or letter in "_"):
                StrippedFileName.append(letter.lower())
        StrippedFileName=''.join(StrippedFileName)
        if(Extension.lower() in ('jpg', 'png', 'jpeg', 'bmp')):
            BackgroundDepartment.BackgroundImageFileName = StrippedFileName
            destination=open('/var/www/intranetbackgroundimages/' + str(StrippedFileName), 'wb+')
            for chunk in DepartmentBackgroundImage.chunks():
                destination.write(chunk)
            destination.close()
            BackgroundDepartment.save()
       
    SelectEventid=COOPIP_Form.FormGetInteger(form, 'SelectEvent')
    EventUpdateIndicator=COOPIP_Form.FormGetBoolean(form, 'EventUpdateIndicator')
    EventNewIndicator=COOPIP_Form.FormGetBoolean(form, 'EventNewIndicator')
    if(EventNewIndicator):
        SelectedEvent=djangoproject.models.intranet.Event()
    elif(not SelectEventid == -1 and SelectEventid):
        SelectedEvent=djangoproject.models.intranet.Event.objects.filter(id=SelectEventid)[0]
    else:
        SelectedEvent='NoEventProcessingPossible'
    if(not SelectedEvent == 'NoEventProcessingPossible') and (EventUpdateIndicator or EventNewIndicator):
        SelectedEvent.Name=COOPIP_Form.FormGetString(form, 'EventName')
        SelectedEvent.StaffOnlyIndicator=COOPIP_Form.FormGetString(form, 'EventStaffOnlyIndicator')
        SelectedEvent.DoNotShowBeforeDateTime=COOPIP_Form.FormGetDateTime(form, 'EventDoNotShowBeforeDateTime')
        SelectedEvent.StartDateTime=COOPIP_Form.FormGetDateTime(form, 'EventStartDateTime')      
        SelectedEvent.EndDateTime=COOPIP_Form.FormGetDateTime(form, 'EventEndDateTime')
        SelectedEvent.Resource=COOPIP_Form.FormGetString(form, 'EventResource')
        SelectedEvent.FrontPageIndicator=COOPIP_Form.FormGetBoolean(form, 'EventFrontPageIndicator')
        SelectedEvent.ArchiveIndicator=COOPIP_Form.FormGetBoolean(form, 'EventArchiveIndicator')
        SelectedEvent.ArchiveOverrideDateTime=COOPIP_Form.FormGetDateTime(form, 'EventArchiveOverrideDateTime')
        EventDepartment=djangoproject.models.intranet.Department()
        if(not EventNewIndicator): #Check to make sure that the events old department may be changed by the user
            GroupList=[SelectedEvent.Department.EditorGroupName]
            Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, GroupList, True)
            if(not Permission):
                return None, SelectedEvent
        SelectedEvent.Department=COOPIP_Form.FormGetObjectFromid(form, 'EventDepartment', djangoproject.models.intranet.Department)
        #Check To make sure that the events new department may be edited by the user
        GroupList=[SelectedEvent.Department.EditorGroupName]
        Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, GroupList, True)
        if(Permission):
            SelectedEvent.save()
    if(SelectedEvent == 'NoEventProcessingPossible'):
       SelectedEvent=None

    if(SelectedMessage == 'NoMessageProcessingPossible'):
        return None, SelectedEvent
    if(NewIndicator or UpdateIndicator):
        if(NewIndicator):
            SelectedMessage.CreateDateTime=datetime.datetime.now()
            SelectedMessage.CreateUsername=Username
            SelectedMessage.LastEditDateTime=datetime.datetime.now()
            SelectedMessage.LastEditUsername=Username
        else:
            SelectedMessage.LastEditDateTime=datetime.datetime.now()
            SelectedMessage.LastEditUsername=Username
        SelectedMessage.Title=COOPIP_Form.FormGetString(form, 'Title')
        SelectedMessage.MessageText=COOPIP_Form.FormGetString(form, 'MessageText')
        SelectedMessage.FrontPageIndicator=COOPIP_Form.FormGetBoolean(form, 'FrontPageIndicator')
        SelectedMessage.Priority=COOPIP_Form.FormGetFloat(form, 'Priority')
        SelectedMessage.DepartmentPageIndicator=COOPIP_Form.FormGetBoolean(form, 'DepartmentPageIndicator')
        if(not NewIndicator and SelectedMessage.Department): #Check to make sure that the messages old department may be changed by the user
            GroupList=[SelectedMessage.Department.EditorGroupName]
            Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, GroupList, True)
            if(not Permission):
                return None, SelectedEvent

        department=djangoproject.models.intranet.Department()
        SelectedMessage.Department=COOPIP_Form.FormGetObjectFromid(form, 'Department', djangoproject.models.intranet.Department)
        #Check To make sure that the messages new department may be edited by the user
        GroupList=[SelectedMessage.Department.EditorGroupName]
        Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, GroupList, True)
        if(not Permission):
            return None, SelectedEvent
        #raise('IT Testing in Progress.')
        SelectedMessage.ArchiveIndicator=COOPIP_Form.FormGetBoolean(form, 'ArchiveIndicator')
        SelectedMessage.ExpireDateTime=COOPIP_Form.FormGetDateTime(form, 'ExpireDateTime')            
        SelectedMessage.save()

    if(SelectedMessage and UploadFile and UpdateIndicator):   #Process File Uploading
        BaseFileName=str(UploadFile).split('.')[0]
        Extension=str(UploadFile).split('.')[-1]
        FileName=str(BaseFileName + '.' + Extension)
        try:
            messageFile=djangoproject.models.intranet.MessageFile.objects.filter(Message=SelectedMessage).filter(FileName=FileName)[0]
        except:
            messageFile=djangoproject.models.intranet.MessageFile()
            messageFile.FileName=FileName
            messageFile.Message=SelectedMessage
            messageFile.save()
        messageFile.File=str(messageFile.id)
        destination=open(djangoproject.settings.MEDIA_ROOT + 'message/' + str(messageFile.id), 'wb+')
        for chunk in UploadFile.chunks():
            destination.write(chunk)
        destination.close()
        messageFile.DateTime=datetime.datetime.now()
        messageFile.save()
    DeleteFile=COOPIP_Form.FormGetString(form, 'DeleteFile')
    DeleteFileIndicator=COOPIP_Form.FormGetBoolean(form, 'DeleteFileIndicator')
    if(SelectedMessage and DeleteFileIndicator and DeleteFile and UpdateIndicator):
        try:
            messageFile=djangoproject.models.intranet.MessageFile.objects.filter(Message=SelectedMessage).filter(FileName=DeleteFile)[0]
            os.remove(djangoproject.settings.MEDIA_ROOT + 'message/' + str(messageFile.id))
            messageFile.delete()
        except:
            pass
    return SelectedMessage, SelectedEvent

def PopulateMessageForm(form, message, event):
    form.data['UpdateIndicator']=False
    form.data['NewIndicator']=False
    form.data['UploadFile']=''
    form.data['DeleteFile']=''
    form.data['DeleteFileIndicator']=False
    form.data['EventUpdateIndicator']=False
    form.data['EventNewIndicator']=False
    if(event):
        form.data['SelectEvent']=event.id
        form.data['Eventid']=event.id
        form.data['EventName']=event.Name
        form.data['EventDoNotShowBeforeDateTime']=event.DoNotShowBeforeDateTime
        form.data['EventStartDateTime']=event.StartDateTime
        form.data['EventEndDateTime']=event.EndDateTime
        form.data['EventResource']=event.Resource
        form.data['EventFrontPageIndicator']=event.FrontPageIndicator
        form.data['EventArchiveIndicator']=event.ArchiveIndicator
        form.data['EventArchiveOverrideDateTime']=event.ArchiveOverrideDateTime
        form.data['EventDepartment']=event.Department
        form.data['EventStaffOnlyIndicator']=event.StaffOnlyIndicator
    else:
        form.data['SelectEvent']=-1
        form.data['EventName']=''
        form.data['Eventid']=''
        form.data['EventDoNotShowBeforeDateTime']=''
        form.data['EventStartDateTime']=''
        form.data['EventEndDateTime']=''
        form.data['EventResource']=''
        form.data['EventFrontPageIndicator']=False
        form.data['EventArchiveIndicator']=False
        form.data['EventArchiveOverrideDateTime']=''
        form.data['EventDepartment']=-1
        form.data['EventStaffOnlyIndicator']=False

    if(message):
        form.data['SelectMessage']=message.id
        form.data['Messageid']=message.id
        form.data['Title']=message.Title
        form.data['MessageText']=message.MessageText
        form.data['FrontPageIndicator']=message.FrontPageIndicator
        form.data['DepartmentPageIndicator']=message.DepartmentPageIndicator
        form.data['Department']=message.Department.id
        form.data['CreateUsername']=message.CreateUsername
        form.data['CreateDateTime']=message.CreateDateTime
        form.data['LastEditUsername']=message.LastEditUsername
        form.data['LastEditDateTime']=message.LastEditDateTime
        form.data['ExpireDateTime']=message.ExpireDateTime
        form.data['ArchiveIndicator']=message.ArchiveIndicator
        form.data['Priority']=message.Priority
    else:
        form.data['SelectMessage']=-1
        form.data['Messageid']=''
        form.data['Title']=''
        form.data['MessageText']=''
        form.data['FrontPageIndicator']=False
        form.data['DepartmentPageIndicator']=False
        form.data['Department']=-1
        form.data['CreateUsername']=''
        form.data['CreateDateTime']=''
        form.data['LastEditUsername']=''
        form.data['LastEditDateTime']=''
        form.data['ExpireDateTime']=''
        form.data['ArchiveIndicator']=False        
        form.data['Priority']=''
    return form







def BuildMeterPingReportForm(SpecialBuildFormDataDict):
    Dict={}
    Dict['AllMeterIndicator']=forms.BooleanField(required=False)
    Dict['AllFailureMeterIndicator']=forms.BooleanField(required=False)
    Dict['AllAMRFailureMeterIndicator']=forms.BooleanField(required=False)
    Dict['AllSubstationFailureMeterIndicator']=forms.BooleanField(required=False)
    Dict['TopOneIndicator']=forms.BooleanField(required=False)
    Dict['SerialNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'20'}))
    Dict['Substation']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'20'}))
    Dict['StartDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'20'}))
    Dict['EndDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'20'}))
    return Dict




def ProcessMeterPingReportForm(form, Username, request):
    AllMeterIndicator=COOPIP_Form.FormGetBoolean(form, 'AllMeterIndicator')
    AllFailureMeterIndicator=COOPIP_Form.FormGetBoolean(form, 'AllFailureMeterIndicator')
    AllAMRFailureMeterIndicator=COOPIP_Form.FormGetBoolean(form, 'AllAMRFailureMeterIndicator')
    AllSubstationFailureMeterIndicator=COOPIP_Form.FormGetBoolean(form, 'AllSubstationFailureMeterIndicator')
    TopOneIndicator=COOPIP_Form.FormGetBoolean(form, 'TopOneIndicator')
    SerialNumber=COOPIP_Form.FormGetString(form, 'SerialNumber')
    Substation=COOPIP_Form.FormGetString(form, 'Substation')    #TODO
    StartDate=COOPIP_Form.FormGetDateTime(form, 'StartDate')
    EndDate=COOPIP_Form.FormGetDateTime(form, 'EndDate')

   
    if(AllMeterIndicator):
        Meters=djangoproject.models.ipbase.Meter.objects.all().order_by('SerialNumber')
    elif(AllFailureMeterIndicator):
        Meters=djangoproject.models.ipbase.Meter.objects.all().filter(Symbology='failed').order_by('SerialNumber')
    elif(AllAMRFailureMeterIndicator):
        Meters=djangoproject.models.ipbase.Meter.objects.all().filter(Symbology='amrfailure').order_by('SerialNumber')
    elif(AllSubstationFailureMeterIndicator):
        Meters=djangoproject.models.ipbase.Meter.objects.all().filter(Symbology='substationfailure').order_by('SerialNumber')
    elif(SerialNumber):
        Meters=djangoproject.models.ipbase.Meter.objects.filter(SerialNumber=SerialNumber)
    else:
        return []
    if(not StartDate):
        StartDate=datetime.datetime.now() - datetime.timedelta(days=2)
    if(not EndDate):
        EndDate=datetime.datetime.now() + datetime.timedelta(days=2)
    MeterPings=[]
    for meter in Meters:
        TempMeterPings=djangoproject.models.ipbase.MeterPing.objects.filter(SerialNumber=meter.SerialNumber).filter(DateTime__gte=StartDate).filter(DateTime__lte=EndDate).order_by('DateTime')
        for meterPing in TempMeterPings:
            MeterPings.append(meterPing)
            if(TopOneIndicator):
                break
    return MeterPings

        


def BuildDispatchAlarmForm(SpecialBuildFormDataDict):
    Dict={}
    NumberOfAlarms=COOPIP_FormNetworkDevice.objects.filter(ActiveIndicator=True).filter(NetworkDeviceModel__Name == 'DSC 1832 Alarm').count()

    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['CrewList']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'10', 'cols':'80'}))
    Dict['EngineerList']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'10', 'cols':'80'}))
    Dict['ServiceWorkerList']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'10', 'cols':'80'}))
    Dict['Message']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'10', 'cols':'80'}))
    Dict['OutOfOffice']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'10', 'cols':'80'}))
    Dict['ServiceWorkerHours']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'10', 'cols':'80'}))
    return Dict

def ProcessDispatchAlarmForm(form, Username, request):
    UpdateIndicator=COOPIP_Form.FormGetBoolean(form, 'UpdateIndicator')
    CrewList=COOPIP_Form.FormGetString(form, 'CrewList')
    EngineerList=COOPIP_Form.FormGetString(form, 'EngineerList')
    ServiceWorkerList=COOPIP_Form.FormGetString(form, 'ServiceWorkerList')
    Message=COOPIP_Form.FormGetString(form, 'Message')
    OutOfOffice=COOPIP_Form.FormGetString(form, 'OutOfOffice')
    ServiceWorkerHours=COOPIP_Form.FormGetString(form, 'ServiceWorkerHours')
    if(UpdateIndicator):
        dispatchBoardForm=djangoproject.models.intranet.DispatchBoard()
        dispatchBoardForm.CrewList=CrewList
        dispatchBoardForm.EngineerList=EngineerList
        dispatchBoardForm.ServiceWorkerList=ServiceWorkerList
        dispatchBoardForm.Message=Message
        dispatchBoardForm.OutOfOffice=OutOfOffice
        dispatchBoardForm.ServiceWorkerHours=ServiceWorkerHours
        dispatchBoardForm.CreateUsername=Username
        dispatchBoardForm.CreateDateTime=datetime.datetime.now()
        dispatchBoardForm.save()


def PopulateDispatchAlarmForm(form):
    form.data['UpdateIndicator']=False
    DispatchBoards=djangoproject.models.intranet.DispatchBoard.objects.all().order_by('-CreateDateTime')
    if(DispatchBoards.count()):
        form.setData({'CrewList': DispatchBoards[0].CrewList})
        form.setData({'EngineerList': DispatchBoards[0].EngineerList})
        form.setData({'ServiceWorkerList': DispatchBoards[0].ServiceWorkerList})
        form.setData({'Message': DispatchBoards[0].Message})
        form.setData({'OutOfOffice': DispatchBoards[0].OutOfOffice})
        form.setData({'ServiceWorkerHours': DispatchBoards[0].ServiceWorkerHours})
    else:
        form.data['CrewList']=''
        form.data['EngineerList']=''
        form.data['ServiceWorkerList']=''
        form.data['Message']=''
        form.data['OutOfOffice']=''
        form.data['ServiceWorkerHours']=''
    return form


